import axios from 'axios'
// import { Notification } from 'element-ui'
// 1. axios 封装 百度到处都有
import { getToken } from '../utils/tools' // 获取token
class HttpRequest {
  constructor (baseUrl) {
    this.baseURL = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseURL,
      headers: {}
    }
    // 若token不为空, 则在headers中加入token
    return config
  }
  interceptors (instance, url) {
    instance.interceptors.request.use(config => {
      this.queue[url] = true;
    // 这里是给请求headers里面加token验证
      if (getToken('token')) {
        config.headers.token = getToken('token')
      }
      return config
    }, error => {
      return Promise.reject(error)
    })
    instance.interceptors.response.use(res => { 
      delete this.queue[url]
      const { data, status, headers } = res
      const { result } = data
      //  这里处理数据 将res 中的所需要的东西 解构（解构赋值）出来，再return出来
      return { data, status, headers, result }
    }, error => {
    // 这里对请求错误状态进行提示
    //   if (error.response.status !== 200) {
    //     Notification({
    //       type: 'error',
    //       message: error.response.data.message
    //     })
    //   }
      delete this.queue[url]
      return Promise.reject(error.response)
    })
  }
  request (options) {
    const instance = axios.create()
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest //导出
